package com.zp.oj.controller;

import cn.hutool.core.io.FileUtil;
import com.zp.oj.common.BaseResponse;
import com.zp.oj.common.ErrorCode;
import com.zp.oj.common.ResultUtils;
import com.zp.oj.constant.FileConstant;
import com.zp.oj.exception.BusinessException;
import com.zp.oj.model.dto.file.UploadFileRequest;
import com.zp.oj.model.entity.User;
import com.zp.oj.model.enums.FileUploadBizEnum;
import com.zp.oj.service.UserService;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件接口
 *
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;

    @Value("${logo-img.local-path}")
    private String logoLocPath; // 本地存放资源目录的绝对路径


    /**
     * 文件上传
     *
     * @param multipartFile
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                           HttpServletRequest request) {
        // 上传文件类型
        String biz = "user_avatar";
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        // 判断类型是否允许上传
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 检查文件后缀.大小是否合法
        validFile(multipartFile, fileUploadBizEnum);
        User loginUser = userService.getLoginUser(request);
        // 文件目录：根据业务、用户来划分
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%s", fileUploadBizEnum.getValue(), loginUser.getId(), filename);
        File file = null;
        try {
            // 上传文件
            File userAvatarFile = new File(logoLocPath, filepath);
            log.info("文件保存路径：{}，是否存在：{}", userAvatarFile.getParentFile(), userAvatarFile.getParentFile().exists());
            if(!userAvatarFile.getParentFile().exists()){
                userAvatarFile.getParentFile().mkdir();
            }
            // 这里必须要填绝对路径
            multipartFile.transferTo(userAvatarFile.getAbsoluteFile());
            log.info("文件保存路径：{}", userAvatarFile.getAbsolutePath());
            // 返回可访问地址
            return ResultUtils.success(FileConstant.COS_HOST + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}
